package com.example.demo.程序员面试金典;

/**
 * @author：zzc
 * @date: 2022/9/7
 */
public class 字符串压缩 {

    class Solution {
        // 双指针


        public String compressString(String S) {
            int n = S.length();
            if (n < 2) {
                return S;
            }
            StringBuilder sb = new StringBuilder();
            int slow = 0, fast = 1;
            while (fast < n) {
                if (S.charAt(slow) != S.charAt(fast)) {
                    sb.append(S.charAt(slow)).append(fast - slow);
                    slow = fast;
                }
                ++fast;
            }
            sb.append(S.charAt(fast)).append(fast - slow);

            return sb.toString().length() < n ? sb.toString() : S;

        }
    }

}
